<template>
  <div class="inventory-view">
    <h1>库存管理</h1>
    
    <div class="inventory-controls">
      <div class="search-container">
        <input 
          v-model="searchQuery" 
          placeholder="搜索库存..." 
          class="search-input"
        >
        <button @click="showAddModal = true" class="add-button">
          + 添加库存
        </button>
      </div>
      
      <div class="filter-tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.value"
          :class="{ active: activeTab === tab.value }"
          @click="activeTab = tab.value"
        >
          {{ tab.label }}
        </button>
      </div>
    </div>
    
    <div class="inventory-list">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>食材名称</th>
            <th>当前库存</th>
            <th>单位</th>
            <th>预警值</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr 
            v-for="item in filteredInventory" 
            :key="item.id"
            :class="{
              'low-stock': item.quantity <= item.alertThreshold,
              'out-of-stock': item.quantity === 0
            }"
          >
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>
              <input 
                type="number" 
                v-model.number="item.quantity" 
                @change="updateInventory(item)"
                min="0"
              >
            </td>
            <td>{{ item.unit }}</td>
            <td>{{ item.alertThreshold }}</td>
            <td>
              <span :class="getStatusClass(item)">
                {{ getStatusText(item) }}
              </span>
            </td>
            <td class="actions">
              <button @click="editItem(item)" class="edit-btn">编辑</button>
              <button @click="deleteItem(item.id)" class="delete-btn">删除</button>
              <router-link :to="`/inventory/${item.id}`" class="detail-btn">详情</router-link>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 添加/编辑库存模态框 -->
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>{{ editingItem? '编辑库存项' : '添加新库存项' }}</h2>
        
        <div class="form-group">
          <label>食材名称</label>
          <input v-model="currentItem.name" type="text">
        </div>
        
        <div class="form-group">
          <label>初始数量</label>
          <input v-model.number="currentItem.quantity" type="number" min="0">
        </div>
        
        <div class="form-group">
          <label>单位</label>
          <select v-model="currentItem.unit">
            <option value="克">克</option>
            <option value="千克">千克</option>
            <option value="毫升">毫升</option>
            <option value="升">升</option>
            <option value="个">个</option>
            <option value="包">包</option>
          </select>
        </div>
        
        <div class="form-group">
          <label>预警值</label>
          <input v-model.number="currentItem.alertThreshold" type="number" min="0">
          <small>当库存低于此值时将显示警告</small>
        </div>
        
        <div class="form-group">
          <label>备注</label>
          <textarea v-model="currentItem.notes"></textarea>
        </div>
        
        <div class="modal-actions">
          <button @click="saveItem" class="save-btn">
            {{ editingItem? '更新' : '保存' }}
          </button>
          <button @click="closeModal" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'InventoryView',
  setup() {
    const inventory = ref([])
    const searchQuery = ref('')
    const activeTab = ref('all')
    const showAddModal = ref(false)
    const editingItem = ref(null)
    const currentItem = ref(createEmptyItem())
    
    const tabs = [
      { label: '全部', value: 'all' },
      { label: '充足', value:'sufficient' },
      { label: '不足', value: 'low' },
      { label: '缺货', value: 'out' }
    ]

    // 加载本地数据
    onMounted(() => {
      const savedInventory = localStorage.getItem('inventory')
      if (savedInventory) {
        inventory.value = JSON.parse(savedInventory)
      } else {
        // 初始化示例数据
        inventory.value = [
          { id: 1, name: '鸡胸肉', quantity: 15, unit: '千克', alertThreshold: 5, notes: '冷冻保存' },
          { id: 2, name: '生菜', quantity: 8, unit: '千克', alertThreshold: 3, notes: '冷藏保存' },
          { id: 3, name: '橄榄油', quantity: 2, unit: '升', alertThreshold: 1, notes: '避光保存' },
          { id: 4, name: '番茄', quantity: 0, unit: '千克', alertThreshold: 2, notes: '已缺货' }
        ]
        saveToLocalStorage()
      }
    })

    // 保存到本地存储
    const saveToLocalStorage = () => {
      localStorage.setItem('inventory', JSON.stringify(inventory.value))
    }

    // 创建空库存项模板
    function createEmptyItem() {
      return {
        id: null,
        name: '',
        quantity: 0,
        unit: '克',
        alertThreshold: 0,
        notes: ''
      }
    }

    // 获取状态文本
    const getStatusText = (item) => {
      if (item.quantity === 0) return '缺货'
      if (item.quantity <= item.alertThreshold) return '库存不足'
      return '库存充足'
    }

    // 获取状态类
    const getStatusClass = (item) => {
      if (item.quantity === 0) return'status-out'
      if (item.quantity <= item.alertThreshold) return'status-low'
      return'status-sufficient'
    }

    // 过滤库存项
    const filteredInventory = computed(() => {
      let result = inventory.value.filter(item => {
        if (item.name.includes(searchQuery.value)) {
          if (activeTab.value!== 'all') {
            if (activeTab.value ==='sufficient') {
              return item.quantity > item.alertThreshold
            }
            if (activeTab.value === 'low') {
              return item.quantity <= item.alertThreshold && item.quantity > 0
            }
            if (activeTab.value === 'out') {
              return item.quantity === 0
            }
            return true
          }
          return true
        }
        return false
      })
      return result
    })

    // 更新库存数量
    const updateInventory = (item) => {
      if (item.quantity < 0) item.quantity = 0
      saveToLocalStorage()
    }

    // 添加/编辑库存项
    const saveItem = () => {
      if (editingItem.value) {
        // 更新现有项
        const index = inventory.value.findIndex(i => i.id === currentItem.value.id)
        if (index!== -1) {
          inventory.value[index] = {...currentItem.value }
        }
      } else {
        // 添加新项
        const newId = inventory.value.length > 0? 
          Math.max(...inventory.value.map(i => i.id)) + 1 : 1
        inventory.value.push({
         ...currentItem.value,
          id: newId
        })
      }
      saveToLocalStorage()
      closeModal()
    }

    // 编辑库存项
    const editItem = (item) => {
      currentItem.value = {...item }
      editingItem.value = true
      showAddModal.value = true
    }

    // 删除库存项
    const deleteItem = (id) => {
      if (confirm('确定要删除这个库存项吗？')) {
        inventory.value = inventory.value.filter(i => i.id!== id)
        saveToLocalStorage()
      }
    }

    // 关闭模态框
    const closeModal = () => {
      showAddModal.value = false
      editingItem.value = null
      currentItem.value = createEmptyItem()
    }

    return {
      inventory,
      searchQuery,
      activeTab,
      tabs,
      showAddModal,
      editingItem,
      currentItem,
      filteredInventory,
      getStatusText,
      getStatusClass,
      updateInventory,
      editItem,
      deleteItem,
      saveItem,
      closeModal
    }
  }
}
</script>

<style scoped>
.inventory-view {
  padding: 20px;
}

.inventory-controls {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.add-button {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.filter-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.filter-tabs button {
  padding: 8px 16px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.filter-tabs button.active {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.inventory-list {
  width: 100%;
  overflow-x: auto;
}

.inventory-list table {
  width: 100%;
  border-collapse: collapse;
}

.inventory-list th, 
.inventory-list td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.inventory-list th {
  background-color: #f8f9fa;
}

.inventory-list input[type="number"] {
  width: 80px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 3px;
}

.low-stock {
  background-color: #fff3cd;
}

.out-of-stock {
  background-color: #f8d7da;
}

.status-sufficient {
  color: #28a745;
  font-weight: bold;
}

.status-low {
  color: #ffc107;
  font-weight: bold;
}

.status-out {
  color: #dc3545;
  font-weight: bold;
}

.actions {
  display: flex;
  gap: 5px;
}

.edit-btn {
  padding: 5px 10px;
  background-color: #17a2b8;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.delete-btn {
  padding: 5px 10px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.detail-btn {
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
  margin-left: 5px;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 500px;
  max-width: 90%;
  position: relative;
}

.close {
  position: absolute;
  top: 10px;
  right: 20px;
  font-size: 24;
  cursor: pointer;
}

.form-group {
  margin-bottom: 15;
}

.form-group label {
  display: block;
  margin-bottom: 5;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group textarea {
  height: 80px;
}

.form-group small {
  color: #6c757d;
  font-size: 12px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.save-btn {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>